Imports System.Xml
Imports System.IO
Imports System.Runtime.Serialization

<Serializable()> _
Public Class Employee
    Implements IComparable(Of Employee)

    <DebuggerDisplay("\{ Exception = {Exception}, Day = {Day} \}")> _
    Private NotInheritable Class DayException
        Private _exception As TimeRangeException
        Private _day As Day

        Public Sub New(ByVal exception As Object, ByVal day As Day)
            _exception = exception
            _day = day
        End Sub

        Public Overrides Function ToString() As String
            Return String.Format("{{ Exception = {0}, Day = {1} }}", _exception, _day)
        End Function

        Public Property Exception() As TimeRangeException
            Get
                Return _exception
            End Get
            Set(ByVal value As TimeRangeException)
                _exception = value
            End Set
        End Property
        Public Property Day() As Day
            Get
                Return _day
            End Get
            Set(ByVal value As Day)
                _day = value
            End Set
        End Property
    End Class
    'Public Event DataChanged(ByVal Sender As Object, ByVal e As EventArgs)
    Private _DefaultLocation As String
    Property DefaultLocation As String
        Get
            Return _DefaultLocation
        End Get
        Set(value As String)
            For Each d In From dy In Me.Days Where dy.StartTimes.Count > 0

                Dim locs() As String
                If d.Locations.Count = 0 Then
                    locs = Enumerable.Repeat(Me.DefaultLocation, d.StartTimes.Count).ToArray
                Else
                    locs = d.Locations
                    For x As Integer = 0 To locs.Count - 1
                        If locs(x) = Me.DefaultLocation Then
                            locs(x) = value
                        End If
                    Next
                End If
                d.Locations = locs

            Next
                    _DefaultLocation = value
        End Set
    End Property

    Private _Color As Nullable(Of Color)
    '<Xml.Serialization.XmlElement(datatype:="System.Drawing.Color", IsNullable:=True)> _
    <Xml.Serialization.XmlIgnore()> _
    Public Property Color() As Nullable(Of Color)
        Get
            Return _Color
        End Get
        Set(ByVal value As Nullable(Of Color))
            _Color = value
        End Set
    End Property
    'Public Overridable Sub OnDataChanged()
    '    RaiseEvent DataChanged(Me, EventArgs.Empty)
    'End Sub
    <Xml.Serialization.XmlIgnore(), System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> _
    Public Property ColorSpecified() As Boolean
        Get
            Return Color.HasValue
        End Get
        Set(ByVal value As Boolean)
            'newPropertyValue = value
        End Set
    End Property

    <Xml.Serialization.XmlElement(ElementName:="Color", IsNullable:=True)>
 <System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)>
 <System.ComponentModel.Browsable(False)>
    Public Property ColorString() As String
        Get
            If Me.Color.HasValue Then
                Return ColorTranslator.ToHtml(Me.Color)
            Else
                Return Nothing
            End If

        End Get
        Set(ByVal value As String)
            If String.IsNullOrEmpty(value) Then
                Me.Color = Nothing
            Else
                Me.Color = ColorTranslator.FromHtml(value)
            End If
        End Set
    End Property
    Private _EmployeeType As String
    <Xml.Serialization.XmlElement(ElementName:="EmployeeType", IsNullable:=True)>
    Property EmployeeType As String
        Get
            Return _EmployeeType
        End Get
        Set(value As String)
            For Each d In From dy In Me.Days Where dy.StartTimes.Count > 0


                If d.ScheduleEmployeeTypes.Count = 0 Then
                    d.ScheduleEmployeeTypes = Enumerable.Repeat(value, d.StartTimes.Count).ToList
                Else
                    Dim est As List(Of String) = d.ScheduleEmployeeTypes

                    For x As Integer = 0 To d.ScheduleEmployeeTypes.Count - 1
                        If d.ScheduleEmployeeTypes(x) = Me.EmployeeType Then
                            d.ScheduleEmployeeTypes(x) = value
                        End If
                    Next
                End If

            Next
            _EmployeeType = value

        End Set
    End Property




    Private _ID As Guid
    Public Property ID() As Guid
        Get
            Return _ID
        End Get
        Set(ByVal value As Guid)
            _ID = value
        End Set
    End Property





    Private _HireDate As Date?
    Public Property HireDate() As Date?
        Get
            Return _HireDate
        End Get
        Set(ByVal value As Date?)
            _HireDate = value
        End Set
    End Property

    Private _FireDate As Date?
    Public Property FireDate() As Date?
        Get
            Return _FireDate
        End Get
        Set(ByVal value As Date?)
            _FireDate = value
        End Set
    End Property



    Private _Name As String
    Public Property Name() As String
        Get
            Return _Name
        End Get
        Set(ByVal value As String)
            _Name = value
        End Set
    End Property

    Private _Holidays As New List(Of HolidayInfo)
    <Xml.Serialization.XmlArray("Holidays"), _
    Xml.Serialization.XmlArrayItem("Holiday", GetType(HolidayInfo))> _
    Public Property Holidays() As List(Of HolidayInfo)
        Get
            Return _Holidays
        End Get
        Set(ByVal value As List(Of HolidayInfo))
            _Holidays = value
        End Set
    End Property





    Public Overrides Function ToString() As String
        If Me.EmployeeType <> "" Then
            Return String.Format("{0} ({1})", Me.Name, Me.EmployeeType)
        Else
            Return Me.Name
        End If
    End Function




    ''' <summary>
    ''' Counts the total hours for an employee at a specified time.
    ''' </summary>
    ''' <param name="CountDate">The date to count from.  Pass Nothing to use Now.Date</param>
    ''' <value></value>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public ReadOnly Property TotalHours(WorkHours As WorkHoursSettings, ByVal CountDate? As Date, Optional ByVal AllHolidays As HolidayInfoList = Nothing, Optional ScheduleTypes As List(Of String) = Nothing) As Double
        Get
            Dim Tothours As Double
            If Not CountDate.HasValue Then CountDate = Now.Date
            Dim wtEs = From wte In WorkHours.SettingsExceptions Where wte.ExceptionDate <= GetNextDay(DayOfWeek.Saturday, CountDate.Value) AndAlso wte.ExceptionDate >= GetLastDay(DayOfWeek.Sunday, CountDate.Value)

            Dim wteTimeIntervals As List(Of DevExpress.XtraScheduler.TimeInterval) = wtEs.Select(Function(wt)
                                                                                                     Return wt.ToTimeOfDayInterval.ToTimeInterval(wt.ExceptionDate)
                                                                                                 End Function).ToList

            Dim tmpdate = GetLastDay(DayOfWeek.Sunday, CountDate.Value)

            For Each dy As Day In Me.Days
                For Each st As Date In dy.StartTimes

                    Dim endDt As Date = dy.EndTimes(Array.IndexOf(dy.StartTimes, st))
                    Dim ti As New DevExpress.XtraScheduler.TimeInterval(st, endDt)
                    Dim schtype As String = dy.ScheduleEmployeeTypes(Array.IndexOf(dy.StartTimes, st))

                    '## Exclude work time exceptions
                    Dim dayTi As DevExpress.XtraScheduler.TimeInterval = (New DevExpress.XtraScheduler.TimeOfDayInterval(st.TimeOfDay, endDt.TimeOfDay)) _
                                                                         .ToTimeInterval(tmpdate)
                    For Each wti In wteTimeIntervals
                        If wti.Start.Date = tmpdate Then

                            Dim ExcludeTi As DevExpress.XtraScheduler.TimeIntervalCollection = WorkHours.DayToWorkingTimeInterval(tmpdate, True).Subtract(wti)
                            If ExcludeTi(0).IntersectsWith(dayTi) Then
                                Tothours -= ExcludeTi(0).Intersect(dayTi).Duration.TotalHours
                            End If
                        End If
                    Next
                    '##

                    If CountDate >= ti.Start.Date.Date AndAlso CountDate <= ti.End.Date Then
                        If (schtype = "") OrElse (ScheduleTypes IsNot Nothing AndAlso ScheduleTypes.Count = 0) OrElse ScheduleTypes.Contains(schtype) Then
                            Tothours += GetDayTimeSpanFromDateRange(st, endDt).Duration.TotalHours
                        End If
                    End If

                Next

                tmpdate = tmpdate.AddDays(1)
            Next
            If My.Settings.CalculateHoursWithExceptions Then
                Dim exc As IEnumerable(Of DayException)


                exc = From d In Days _
                From ex In d.TimeExceptions _
                    Where ex.Day.Date <= GetNextDay(DayOfWeek.Saturday, CountDate) And ex.Day >= GetLastDay(DayOfWeek.Sunday, CountDate) _
                    Select New DayException(ex, d)

                For Each dex In exc
                    Select Case dex.Exception.ExceptionType
                        Case ExceptionTypes.Add
                            Tothours += dex.Exception.EndTime.Subtract(dex.Exception.StartTime).Duration.TotalHours

                        Case ExceptionTypes.Replace

                            Tothours -= GetDayTimeSpanFromDateRange(dex.Day.StartTimes(dex.Exception.TimeRange), dex.Day.EndTimes(dex.Exception.TimeRange)).TotalHours
                            Tothours += GetDayTimeSpanFromDateRange(dex.Exception.StartTime, dex.Exception.EndTime).TotalHours
                        Case ExceptionTypes.Delete
                            Tothours -= GetDayTimeSpanFromDateRange(dex.Day.StartTimes(dex.Exception.TimeRange), dex.Day.EndTimes(dex.Exception.TimeRange)).TotalHours

                    End Select
                Next








                Dim hol As New HolidayInfoList

                Dim emphol As IEnumerable(Of HolidayInfo) = From h In Me.Holidays _
                                                         Where h.Day <= GetNextDay(DayOfWeek.Saturday, CountDate) AndAlso h.Day >= GetLastDay(DayOfWeek.Sunday, CountDate)

                hol.AddRange(emphol.ToArray)

                If AllHolidays IsNot Nothing AndAlso AllHolidays.Count <> 0 Then
                    Dim allhol = From h In AllHolidays _
                                 Where h.Day <= GetNextDay(DayOfWeek.Saturday, CountDate) AndAlso h.Day >= GetLastDay(DayOfWeek.Sunday, CountDate)

                    hol.AddRange(allhol.ToArray)
                End If
                Dim dts As New List(Of Date)
                For Each hi In hol

                    Dim dt As Date = hi.Day
                    Dim endt As Date = If(hi.EndDate.HasValue, hi.EndDate.Value, hi.Day)
                    Do While dt <= endt
                        If Not dts.Contains(dt) Then
                            For x As Integer = 0 To Days(dt.DayOfWeek).StartTimes.Count - 1
                                Tothours -= GetDayTimeSpanFromDateRange(Days(dt.DayOfWeek).StartTimes(x), Days(dt.DayOfWeek).EndTimes(x)).TotalHours

                            Next
                            dts.Add(dt)
                        End If
                        dt = dt.AddDays(1)
                    Loop

                Next
            End If

            Return Tothours
        End Get

    End Property

    Public Function getUniqueScheduleTypes() As String()
        Return ((From d In Me.Days Select d.ScheduleEmployeeTypes Distinct).SelectMany(Function(st)
                                                                                           Return st
                                                                                       End Function).Union(From d In Me.Days From tr In d.TimeExceptions Select tr.ScheduleType).Distinct).ToArray
    End Function
    Public Function getUniqueLocations() As String()
        Return ((From d In Me.Days Select d.Locations Distinct).SelectMany(Function(st)
                                                                               Return st
                                                                           End Function).Union(From d In Me.Days From tr In d.TimeExceptions Select tr.Location).Distinct).ToArray
    End Function
    Private _days As Day() = {New Day("Sunday"), New Day("Monday"), New Day("Tuesday"), New Day("Wednesday"), New Day("Thursday"), New Day("Friday"), New Day("Saturday")}

    Public Property Days() As Day()
        Get
            Return _days
        End Get
        Set(ByVal value As Day())
            _days = value
        End Set

    End Property


    Public Sub New()
        ID = Guid.NewGuid
    End Sub
    Public Sub New(ByVal Name As String)
        Me.Name = Name
        ID = Guid.NewGuid
    End Sub
    Public Sub New(ByVal Name As String, ByVal Holidays As List(Of HolidayInfo))
        MyClass.New(Name)
        Me.Holidays = Holidays
    End Sub


    Public Function CompareTo(ByVal other As Employee) As Integer Implements System.IComparable(Of Employee).CompareTo
        Return Me.Name.CompareTo(other.Name)

    End Function
End Class

<Serializable(), _
Xml.Serialization.XmlRoot("Employees")> _
Public Class EmployeeList
    Inherits List(Of Employee)
    Implements IDisposable
    Private Shared logger As NLog.Logger = NLog.LogManager.GetCurrentClassLogger()
    <Xml.Serialization.XmlElement("filters", GetType(SerializableDictionary(Of String, String)), isnullable:=True)>
    Property Filters As New SerializableDictionary(Of String, String)

    Private _IsSigned As Boolean
    Public ReadOnly Property IsSigned() As Boolean
        Get
            Return _IsSigned
        End Get
    End Property
    Private _WorkHours As WorkHoursSettings
    <Xml.Serialization.XmlElement("WorkHours", GetType(WorkHoursSettings))> _
    Public Property WorkHours() As WorkHoursSettings
        Get
            Return _WorkHours
        End Get
        Set(ByVal value As WorkHoursSettings)
            _WorkHours = value
        End Set
    End Property
    <Xml.Serialization.XmlElement("ScheduleColors", GetType(ScheduleColorSetting), isnullable:=True)>
    Property ScheduleColors As New ScheduleColorSetting

    Public Function GetTotalHours(DateofWeek As Date) As Double
        Return (From e In Me).Sum(Function(e)
                                      Return e.TotalHours(Me.WorkHours, DateofWeek)
                                  End Function)
    End Function
    Public Function GetUniqueEmployeeTypes() As List(Of String)
        Return (From e In Me Where Not String.IsNullOrWhiteSpace(e.EmployeeType) Order By e.EmployeeType Select e.EmployeeType Distinct).ToList

    End Function

    Public Function GetUniqueLocations() As List(Of String)
        Return (From e In Me From d In e.Days From l In d.Locations Where Not String.IsNullOrWhiteSpace(l) Order By l Select l).Union(From e In Me From d In e.Days From tr In d.TimeExceptions Where Not String.IsNullOrWhiteSpace(tr.Location) Select tr.Location).Union(From e In Me Where Not String.IsNullOrWhiteSpace(e.DefaultLocation) Select e.DefaultLocation).Distinct().ToList

    End Function
    Public Function GetUniqueScheduleTypes() As List(Of String)
        Return (From e In Me From d In e.Days From st In d.ScheduleEmployeeTypes Where Not String.IsNullOrWhiteSpace(st) Order By st Select st).Union(From e In Me From d In e.Days From tr In d.TimeExceptions Select tr.ScheduleType).Distinct().ToList

    End Function
    Public Sub Save(ByVal pth As String, Optional ByVal Signed As Boolean = False)


        Dim Serializers As Serialization.XmlSerializer() = Serialization.XmlSerializer.FromTypes(New Type() {GetType(EmployeeList),
                                                                                                             GetType(WorkHoursSettings),
                                                                                                             GetType(List(Of HolidayInfo)), GetType(ScheduleColorSetting), GetType(SerializableDictionary(Of String, String))})

        Using mStream As New IO.MemoryStream
            Serializers(0).Serialize(mStream, Me)
            mStream.Seek(0, SeekOrigin.Begin)
            Dim Doc As New Xml.XmlDocument
            Doc.PreserveWhitespace = True
            Doc.Load(mStream)
            Using mstream2 As New IO.MemoryStream
                Dim doc2 As New XmlDocument
                doc2.PreserveWhitespace = True
                Serializers(1).Serialize(mstream2, Me.WorkHours)
                mstream2.Seek(0, SeekOrigin.Begin)
                doc2.Load(mstream2)
                Doc.DocumentElement.AppendChild(Doc.ImportNode(doc2.DocumentElement, True))

            End Using
            Using mstream3 As New IO.MemoryStream
                Dim doc3 As New XmlDocument
                doc3.PreserveWhitespace = True
                Serializers(2).Serialize(mstream3, Me.Holidays)
                mstream3.Seek(0, SeekOrigin.Begin)
                doc3.Load(mstream3)
                Dim xe As XmlElement = Doc.CreateElement("Holidays")
                xe.InnerXml = doc3.DocumentElement.InnerXml
                Doc.DocumentElement.AppendChild(xe)

            End Using
            Using mstream4 As New IO.MemoryStream
                Dim doc4 As New XmlDocument
                doc4.PreserveWhitespace = True
                Serializers(3).Serialize(mstream4, Me.ScheduleColors)
                mstream4.Seek(0, SeekOrigin.Begin)
                doc4.Load(mstream4)
                Dim xe As XmlElement = Doc.CreateElement("ScheduleColorSetting")
                xe.InnerXml = doc4.DocumentElement.InnerXml
                Doc.DocumentElement.AppendChild(xe)

            End Using

            Using mstream5 As New IO.MemoryStream
                Dim doc5 As New XmlDocument
                doc5.PreserveWhitespace = True
                Serializers(4).Serialize(mstream5, Me.Filters)
                mstream5.Seek(0, SeekOrigin.Begin)
                Using sr As New IO.StreamReader(mstream5)
                    Dim tmp As String = sr.ReadToEnd

                    mstream5.Seek(0, SeekOrigin.Begin)
                    doc5.Load(mstream5)
                    Dim xe As XmlElement = Doc.CreateElement("filters")
                    xe.InnerXml = doc5.DocumentElement.InnerXml
                    Doc.DocumentElement.AppendChild(xe)
                End Using
            End Using
            If Signed Then myBoss.SignDoc(Doc)
            Doc.Save(pth)



        End Using





    End Sub
    Public Shared Function LoadEmployees(ByVal pth As String) As EmployeeList

        Dim emps As EmployeeList
        Try
            Dim Serializers As Serialization.XmlSerializer() = Serialization.XmlSerializer.FromTypes(New Type() {GetType(EmployeeList),
                                                                                                                 GetType(WorkHoursSettings),
                                                                                                             GetType(HolidayInfoList),
                                                                                                                 GetType(ScheduleColorSetting),
                                                                                                                 GetType(SerializableDictionary(Of String, String))})
           

            Dim bos As New Boss
            Dim verified As Boolean = True
            If bos.IsSigned(pth) Then
                verified = bos.VerifySignature(pth)
            End If
            bos.Dispose()

            If Not verified Then
                If DevExpress.XtraEditors.XtraMessageBox.Show("The file was signed but was modified.  The signature is now invalid.  Do you still want to load this file?", "Invalid Signature", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button2) = DialogResult.No Then Return New EmployeeList
            End If
            Dim doc As New Xml.XmlDocument
            doc.PreserveWhitespace = True
            doc.Load(pth)
            If doc.DocumentElement.Name <> "Employees" Then
                Dim rdoc As New XmlDocument
                rdoc.PreserveWhitespace = True
                rdoc.AppendChild(rdoc.CreateElement("Employees"))
                For Each nd As XmlNode In doc.DocumentElement.ChildNodes
                    rdoc.DocumentElement.AppendChild(rdoc.ImportNode(nd, True))
                Next
                doc = rdoc

                'rdoc.Save(pth)
            End If


            Dim xemps As XElement = XElement.Parse(doc.OuterXml)
            Try

                Dim trs As IEnumerable(Of XElement) = From tr In xemps.Elements("Employee").Elements("Days").Elements("Day").Elements("TimeExceptions").Elements("TimeRangeException") Where tr.Element("ExceptionType").Value = "Remove" Select tr

                For Each xe As XElement In trs
                    xe.Element("ExceptionType").SetValue("Replace")

                Next

            Catch
            End Try




            Using strm As New IO.MemoryStream
                Dim settings As New Xml.XmlWriterSettings
                With settings
                    .Indent = True
                End With
                Using xw As XmlWriter = XmlWriter.Create(strm, settings)
                    xemps.Save(xw)
                End Using
                strm.Seek(0, SeekOrigin.Begin)

                emps = Serializers(0).Deserialize(strm)
                If doc.GetElementsByTagName("WorkHoursSettings").Count = 1 Then
                    Using strm2 As New IO.MemoryStream
                        Dim doc2 As New XmlDocument
                        doc2.LoadXml(doc.GetElementsByTagName("WorkHoursSettings")(0).OuterXml)
                        doc2.Save(strm2)
                        strm2.Seek(0, SeekOrigin.Begin)
                        emps.WorkHours = Serializers(1).Deserialize(strm2)
                    End Using
                    If doc.GetElementsByTagName("ScheduleColorSetting").Count > 0 Then
                        Using strm3 As New IO.MemoryStream
                            Dim doc3 As New XmlDocument

                            doc3.LoadXml(doc.GetElementsByTagName("ScheduleColorSetting")(0).OuterXml)
                            doc3.Save(strm3)
                            strm3.Seek(0, SeekOrigin.Begin)
                            emps.ScheduleColors = Serializers(3).Deserialize(strm3)

                        End Using
                    End If
                End If
                Dim holidays As XmlNode = (From nd As XmlNode In doc.DocumentElement.ChildNodes Where nd.LocalName = "Holidays").FirstOrDefault
                Dim filters As XmlNode = (From nd As XmlNode In doc.DocumentElement.ChildNodes Where nd.LocalName = "filters").FirstOrDefault
                If holidays IsNot Nothing Then
                    Using strm4 As New IO.MemoryStream
                        Dim doc4 As New XmlDocument
                        doc4.LoadXml(holidays.OuterXml)
                        doc4.Save(strm4)
                        strm4.Seek(0, SeekOrigin.Begin)
                        emps.Holidays = Serializers(2).Deserialize(strm4)

                    End Using
                End If
                If filters IsNot Nothing Then
                    Try


                        Using strm5 As New IO.MemoryStream
                            Dim doc5 As New XmlDocument

                            Dim tmp As String = filters.OuterXml
                            tmp = tmp.Replace("filters", "Dictionary")
                            doc5.LoadXml(tmp)

                            doc5.Save(strm5)
                            strm5.Seek(0, SeekOrigin.Begin)




                            emps.Filters = Serializers(4).Deserialize(strm5)



                        End Using
        Catch ex As Exception

        End Try

                End If
            End Using

            emps.FixTimeRanges()
            emps.RemoveSchedulesOutofWorkTime()
            Dim genHolidays As IEnumerable(Of HolidayInfo) = From h In emps(0).Holidays Where h.IsGeneralHoliday

            If emps.Count >= 1 Then
                For Each hi In genHolidays.ToArray

                    emps.Holidays.Add(hi)

                Next
                For Each emp In emps
                    For Each hi In (From h In emp.Holidays Where h.IsGeneralHoliday = True).ToArray
                        emp.Holidays.Remove(hi)
                    Next
                Next
            End If

        Catch ex As Exception
            Return New EmployeeList
        End Try




        Return emps

    End Function
    Sub FixTimeRanges()
        FixTimeRanges(Me)

    End Sub
    Shared Sub FixTimeRanges(ByVal emps As EmployeeList)
        For Each emp As Employee In emps
            For Each D As Day In emp.Days
                Dim strtLst, endlist As New List(Of Date)
                Dim SchTypes As New List(Of String)
                Dim locTypes As New List(Of String)

                For x As Integer = 0 To D.StartTimes.Count - 1
                    Dim StartDt = D.StartTimes(x), EndDt = D.EndTimes(x)
                    If D.StartTimes(x).Date < emps.WorkHours.SemesterStart Then

                        Dim SemStrt As Date = emps.WorkHours.SemesterStart

                        StartDt = New Date(SemStrt.Year, SemStrt.Month, SemStrt.Day, StartDt.Hour, StartDt.Minute, StartDt.Second)

                    End If

                    If D.EndTimes(x).Date > emps.WorkHours.SemesterEnd OrElse D.EndTimes(x).Date < StartDt Then

                        Dim SemEnd As Date = emps.WorkHours.SemesterEnd

                        EndDt = New Date(SemEnd.Year, SemEnd.Month, SemEnd.Day, EndDt.Hour, EndDt.Minute, EndDt.Second)
                    End If
                    strtLst.Add(StartDt)
                    endlist.Add(EndDt)
                    If D.ScheduleEmployeeTypes.Count = 0 Then
                        SchTypes.Add(emp.EmployeeType)
                    Else
                        SchTypes.Add(D.ScheduleEmployeeTypes(x))
                    End If
                    If D.Locations.Count = 0 Then
                        locTypes.Add(emp.DefaultLocation)
                    Else
                        locTypes.Add(D.Locations(x))
                    End If
                Next
                D.Clear(False)
                For x As Integer = 0 To strtLst.Count - 1
                    D.AddTimeRange(strtLst(x), endlist(x), SchTypes(x), locTypes(x))

                Next
            Next
        Next
    End Sub

    Public Sub RemoveSchedulesOutofWorkTime()

        For Each emp As Employee In Me
            For d As Integer = 0 To 6
                Dim dy As Day = emp.Days(d)
                For x As Integer = dy.StartTimes.Count - 1 To 0 Step -1
                    Dim times As Tuple(Of TimeSpan, TimeSpan) = dy.GetDayTimeRange(x)
                    Dim wtimes As Tuple(Of TimeSpan, TimeSpan) = Me.WorkHours.GetDayTimeRange(d)

                    If Not Me.WorkHours.DaysToWork And (2 ^ (d + 1)) OrElse times.Item1 < wtimes.Item1 OrElse times.Item2 > wtimes.Item2 Then
                        dy.RemoveTimeRange(x)
                    End If
                Next

            Next

        Next

    End Sub
    Private _Holidays As HolidayInfoList
    <Xml.Serialization.XmlArray("Holidays"), _
    Xml.Serialization.XmlArrayItem("Holiday", GetType(HolidayInfo))> _
    Public Property Holidays() As HolidayInfoList
        Get
            If _Holidays Is Nothing Then _Holidays = New HolidayInfoList
            Return _Holidays
        End Get
        Set(ByVal value As HolidayInfoList)
            _Holidays = value
        End Set
    End Property
    <NonSerialized()>
    Private myBoss As Boss

    Public ReadOnly Property Boss() As Boss
        Get
            Return myBoss
        End Get
    End Property
    Public Sub New()
        myBoss = New Boss
        _WorkHours = New WorkHoursSettings
    End Sub

#Region "IDisposable Support"
    Private disposedValue As Boolean ' To detect redundant calls

    ' IDisposable
    Protected Overridable Sub Dispose(disposing As Boolean)
        If Not Me.disposedValue Then
            If disposing Then
                ' TODO: dispose managed state (managed objects).
                Me.Boss.Dispose()

            End If

            ' TODO: free unmanaged resources (unmanaged objects) and override Finalize() below.
            ' TODO: set large fields to null.
        End If
        Me.disposedValue = True
    End Sub

    ' TODO: override Finalize() only if Dispose(ByVal disposing As Boolean) above has code to free unmanaged resources.
    'Protected Overrides Sub Finalize()
    '    ' Do not change this code.  Put cleanup code in Dispose(ByVal disposing As Boolean) above.
    '    Dispose(False)
    '    MyBase.Finalize()
    'End Sub

    ' This code added by Visual Basic to correctly implement the disposable pattern.
    Public Sub Dispose() Implements IDisposable.Dispose
        ' Do not change this code.  Put cleanup code in Dispose(disposing As Boolean) above.
        Dispose(True)
        GC.SuppressFinalize(Me)
    End Sub
#End Region

End Class
Public Class PointTag
    Implements ICloneable


    Private _Day As Integer
    Private _TimeRange As Integer
    Property Day() As Integer
        Get
            Return _Day
        End Get
        Set(ByVal value As Integer)
            _Day = value
        End Set
    End Property
    Property TimeRange() As Integer
        Get
            Return _TimeRange
        End Get
        Set(ByVal value As Integer)
            _TimeRange = value
        End Set
    End Property
    Private _timeRangeException As TimeRangeException
    Public Property TimeRangeException() As Lab_Hours.TimeRangeException
        Get
            Return _timeRangeException
        End Get
        Set(ByVal value As Lab_Hours.TimeRangeException)
            _timeRangeException = value
        End Set
    End Property
    Private _Isholiday As Boolean
    Public Property IsHoliday() As Boolean
        Get
            Return _Isholiday
        End Get
        Set(ByVal value As Boolean)
            _Isholiday = value
        End Set
    End Property

    Property Employee As Employee
    Private _Holiday As HolidayInfo
    Public Property Holiday() As HolidayInfo
        Get
            Return _Holiday
        End Get
        Set(ByVal value As HolidayInfo)
            _Holiday = value
        End Set
    End Property


    Private _WorkSettingException As WorkHoursSettings.HourSettingException
    Public Property WorkSettingException() As WorkHoursSettings.HourSettingException
        Get
            Return _WorkSettingException
        End Get
        Set(ByVal value As WorkHoursSettings.HourSettingException)
            _WorkSettingException = value
        End Set
    End Property

    Public Sub New(ByVal Day As Integer, ByVal Time As Integer)
        Me.Day = Day
        TimeRange = Time

    End Sub


    Public Function Clone() As Object Implements System.ICloneable.Clone
        Return MemberwiseClone()

    End Function
End Class